import {createPlaywrightRouter, FileDownload, sleep} from 'crawlee';
import {writeFileSync} from "node:fs";


// createPlaywrightRouter() is only a helper to get better
// intellisense and typings. You can use Router.create() too.
export const router = createPlaywrightRouter();

// This replaces the request.label === DETAIL branch of the if clause.


router.addDefaultHandler(async ({page, enqueueLinks, request, log}) => {
    log.debug(`downloadImage: ${request.url}`);
    // We are now on a category page. We can use this to paginate through and enqueue all products,
    // as well as any subsequent pages we find


    if (request.label == 'image') {
        await page.waitForSelector('#dimg')

        // Start waiting for download before clicking. Note no await.
        const downloadPromise = page.waitForEvent('download');
        await page.click('#dimg > i', {delay: 500});
        await page.click('body > div.layui-dropdown.layui-border-box.layui-panel.layui-anim.layui-anim-downbit > ul > li:nth-child(1) > div.layui-menu-body-title > i', {delay: 500})
        await page.click('body > div.layui-dropdown.layui-border-box.layui-panel.layui-anim.layui-anim-downbit > ul > li:nth-child(1) > div.layui-panel.layui-menu-body-panel > ul > li:nth-child(1)', {delay: 500});
        //await page.locator('body > div.layui-dropdown.layui-border-box.layui-panel.layui-anim.layui-anim-downbit > ul > li:nth-child(1) > div.layui-panel.layui-menu-body-panel > ul > li:nth-child(1) > div').click();


        const download = await downloadPromise;
        await download.saveAs('C:\\Users\\Administrator\\Pictures\\Camera Roll\\' + download.suggestedFilename());
        await page.close();
    } else {

        await page.waitForSelector('#view_photoList')

        await enqueueLinks({
            label: 'image',
            selector: '#view_photoList > div.list-inner.home-list.row.list-xs-6.row-10.row-xs-15 > div > article > div.image > a'
        });

        let current = await page.waitForSelector('.layui-laypage-curr')
        let currentText = await current.textContent();
        let currentNum = (Number.parseInt(currentText ? currentText : "1", 0));
        await enqueueLinks({label: 'pages', urls: ['https://bing.ee123.net/page/' + (currentNum + 1)]});
    }


    /* const crawler = new FileDownload({
         requestHandler({ body, request }) {
             writeFileSync(request.url.replace(/[^a-z0-9\.]/gi, '_'), body);
         },
     });
     await crawler.run([
     ]);*/

});

// This is a fallback route which will handle the start URL
// as well as the LIST labeled URLs.

/*router.addDefaultHandler(async ({request, page, enqueueLinks, log}) => {
    log.debug(`Enqueueing categories from page: ${request.url}`);
    // This means we're on the start page, with no label.
    // On this page, we just want to enqueue all the category pages.
    console.log(request.label)
   /!* await page.waitForSelector('#view_photoList')

    await enqueueLinks({
        label: 'image',
        selector: '#view_photoList > div.list-inner.home-list.row.list-xs-6.row-10.row-xs-15 > div > article > div.image > a'
    });*!/

});*/
